<?php
include_once 'utilities/includes.php';

class comms_upload
{
    public static $PROTOCOL_NAME  = "UPLOAD";    
    public static $STAGE_COMMAND  = "NS_STAGE";    
    public static $STAGE_START    = "START";
    public static $STAGE_DESCRIBE = "DESCRIBE";    
    public static $MSG_NOT_PASSED = "PROTOCOL NOT PASSED";
    public static $MSG_NOT_SET    = "PROTOCOL NOT SET";
    public static $MSG_UNKNOWN    = "PROTOCOL UNKNOWN";
    
    private $post = null;        // The POST command that we are receiving    
    private $stage = null;       // What stage are we at in the upload [ START | DESCRIBE  ]    
    private $metadata = array(); // Array of metadata that is to be stored in DB
    private $result = null;      // Result of the POST that we will give back
    
    public function __construct($post = null)
    {
        $this->post = $post;
        $this->handle_upload();
    }
    
    public function __destruct()
    {
        
    }
    
    private function handle_upload()
    {
        if (!isset($this->post) || is_null($this->post) || isempty($this->post)) 
        {
           $this->result = self::$MSG_NOT_PASSED;
           return;
        }
        
        if (!$this->post[self::$NS_PROTOCOL])
        {
           $this->result = self::$MSG_NOT_SET;
           return;
        }
        
        $this->stage = $this->post[self::$STAGE_COMMAND]; // Find what stage they have said they are at.
        
        switch ($this->stage) 
        {
            case self::$STAGE_START:    $this->starting_upload_process(); break;
            case self::$STAGE_DESCRIBE: $this->describe_uuploaded_file(); break;
            
            default:  $this->unknown_upload_protocol();  break; // Return error if Unknown Protocol
        }        
    }

    public function unknown_upload_protocol()
    {
        $this->result = self::$MSG_UNKNOWN;         
    }
    
    
    /*
     * Generated Random Character String and hand back as an ID for the file.
     */
    public function starting_upload_process()
    {        
        $random_name = tempname("../incoming/", "ns-");
        return $random_name;
    }
    
    /*
     * Take in key and values to describe the uploaded
     */    
    public function describe_uploaded_file()
    {   
        foreach ($this->post as $key => $value)
        {
            if ( substr($key,0,  strlen(self::$NS_PROTOCOL_PREFIX))  == self::$NS_PROTOCOL_PREFIX)
                $this->metadata[str_replace(self::$NS_PROTOCOL_PREFIX, '', $key) ] = $value;            
        }

        logger::variable($this->metedata);
        
        return $this->result;
    }

    /*
     * Look thru post and find any fileds starting with NS_
     */
    private function get_upload_data_fields()
    {
        
    }
    
    
    public function result()
    {
        return $this->result;
    }
      
    
}

?>
